<?php

namespace App\Http\Controllers\admin;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

//友情链接
class Link extends Controller
{
    //友情链接列表
    public function index(Request $request)
    {
        $data['link'] = DB::table('friend_link')->lists();
        $data['page'] = (int)$request->page;//获取分页
        $data['pageSize'] = 3;
        $pages = DB::table('friend_link')->orderBy('id','desc')->pages($data['pageSize']);
        $data['link_list'] = $pages['lists'];
        $data['total']        = $pages['total']; //总数
        return view('admin.friend_link.index',$data);
    }
    //添加及编辑友情链接
    public function add(Request $request)
    {
        $lid = (int)$request->lid;
        $data['item'] = DB::table('friend_link')->where('id',$lid)->item();
        return view('admin.friend_link.add',$data);
    }
    //友情链接保存
    public function save(Request $request)
    {
        $lid   = (int)$request->id;
        $data['title'] = trim($request->title);
        $data['url']   = trim($request->url);
        $data['ord'] = trim($request->ord);
        $data['status'] = $request->status=='on'?1:0;

        if($lid==0 && $data['title']==''){
            exit(json_encode(array('code'=>1,'msg'=>'链接名称不能为空')));
        }
        if ($lid==0){
            $link_name = DB::table('friend_link')->where('title',$data['title'])->first();
            if ($link_name){
                exit(json_encode(array('code'=>1,'msg'=>'该链接名称已存在')));
            }
            $link_url = DB::table('friend_link')->where('url',$data['url'])->first();
            if ($link_url){
                exit(json_encode(array('code'=>1,'msg'=>'该URL链接地址已存在')));
            }
            $data['add_time'] = time();
            DB::table('friend_link')->insert($data);
        }else{
            $data['update_time'] = time();
            DB::table('friend_link')->where('id',$lid)->update($data);
        }
        exit(json_encode(array('code'=>0,'msg'=>'保存成功')));
    }
    //友链删除
    public function del(Request $request)
    {
        $lid = (int)$request->lid;
        DB::table('friend_link')->where('id',$lid)->delete();
        exit(json_encode(array('code'=>0,'msg'=>'删除成功')));
    }
}
